<template>
  <div class="no-background-container">
    <header-component />
    <div style="height: 60px"></div>
    <el-affix :offset="62">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">{{ routeName }}</div>
        </div>
        <div class="header-query">
          <div class="header-query-buttons">
            <!-- 只有在外部部门时显示新增按钮 -->
            <template v-if="isExternalDepartment">
              <el-button type="primary" @click="showAddForm">
                <el-icon class="mr-2"><plus /></el-icon>
                新增外部人员
              </el-button>
              <el-button type="primary" @click="userImportRef?.open()">
                <el-icon class="mr-2"><upload-filled /></el-icon>
                批量导入
              </el-button>
            </template>
            <el-button type="primary" @click="fetchData">
              <el-icon class="mr-2"><refresh /></el-icon>
              刷新
            </el-button>
          </div>
          <query-form-component
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <div class="content-container">
      <!-- 左侧部门树 -->
      <div class="department-tree">
        <department-tree v-model="selectedDepartmentId" @select="handleDepartmentSelect" />
      </div>

      <!-- 右侧用户列表 -->
      <div class="user-list">
        <qs-table
          :finally-columns="finallyColumns"
          :layout="layout"
          :list="list"
          :list-loading="listLoading"
          :query-form="queryForm"
          :total="total"
          @handle-current-change="handleCurrentChange"
          @handle-delete="handleDelete"
          @handle-edit="handleEdit"
          @handle-size-change="handleSizeChange"
          @update:query-form="updateQueryForm"
        />
      </div>
    </div>

    <!-- 表单弹窗 - 使用通用FormDialog组件 -->
    <form-dialog
      v-model="showFormDialog"
      :add-params="addParams"
      :form-data="form"
      :module-name="moduleName"
      :title="isEditMode ? '编辑' : '新增'"
      @submit="handleFormSubmit"
    />

    <!-- 导入弹窗 - 使用新的用户导入组件 -->
    <user-import-component ref="userImportRef" :is-external-user="isExternalDepartment" @success="handleImportSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { Plus, Refresh, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref } from 'vue'
import { useRoute } from 'vue-router'
import DepartmentTree from '../components/DepartmentTree.vue'
import HeaderComponent from '../components/header.vue'
import UserImportComponent from './components/UserImportComponent.vue'
import type { User } from './config'
import { addParams, moduleApi, moduleName, searchParams, tableColumns } from './config'
import Public from '/@/api/public/index'
import FormDialog from '/@/components/FormDialog/index.vue'

// 部门树数据
const selectedDepartmentId = ref<number | string | null>(null)

// 判断是否为外部部门
const isExternalDepartment = computed(() => {
  return (
    selectedDepartmentId.value === 'external' ||
    (typeof selectedDepartmentId.value === 'string' && selectedDepartmentId.value.startsWith('ext-'))
  )
})

// 更新处理部门选择的函数
const handleDepartmentSelect = (data: any) => {
  // 直接使用节点的id，不做转换
  selectedDepartmentId.value = data.id

  // 对于外部部门，需要处理ID前缀用于查询
  let deptId: number | string | null = null
  if (data.isExternal && typeof data.id === 'string' && data.id.startsWith('ext-')) {
    deptId = parseInt(data.id.replace('ext-', ''))
  } else if (data.id !== 'external') {
    // 普通内部部门
    deptId = data.id
  }

  // 更新查询条件并重新获取数据
  queryForm.value = {
    ...queryForm.value,
    deptId,
    page: 1,
  }

  // 打印选中部门信息
  console.log('选中部门:', {
    名称: data.name,
    ID: data.id,
    是否外部: data.isExternal,
    处理后ID: deptId,
    isExternalDepartment: isExternalDepartment.value,
  })

  fetchData()
}

// 表单相关
const form = ref<Partial<User>>({})
const showFormDialog = ref(false)
const isEditMode = ref(false)
const userImportRef = ref()

// 编辑行数据
const handleEdit = (row: User) => {
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}

// 处理表单提交
const handleFormSubmit = async (formData: User) => {
  // 处理职务数据
  if (Array.isArray(formData.postsMiddle)) {
    // 如果是编辑模式，postsMiddle 可能已经是完整的对象数组
    if (formData.postsMiddle.length > 0 && typeof formData.postsMiddle[0] === 'object') {
      formData.postsId = formData.postsMiddle.map((item: any) => item.postsId).join(',')
    } else {
      // 如果是新增模式，postsMiddle 是 ID 数组
      formData.postsId = formData.postsMiddle.join(',')
    }
  } else if (formData.postsMiddle) {
    formData.postsId = formData.postsMiddle.toString()
  }

  try {
    let response
    if (isEditMode.value) {
      response = await Public.editApi({ url: moduleApi, data: formData })
    } else {
      response = await Public.addApi({ url: moduleApi, data: formData })
    }

    const data = response.data || response
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === -1) {
        ElMessage.error('重复添加')
      } else {
        ElMessage.success(isEditMode.value ? '编辑成功' : '添加成功')
      }
    }

    showFormDialog.value = false
    await fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 更新查询表单
const updateQueryForm = (newQueryForm: any) => {
  queryForm.value = { ...newQueryForm }
  // 如果清除了部门ID，也清除部门树的选中状态
  if (!newQueryForm.deptId) {
    selectedDepartmentId.value = null
  }
}

// 获取当前路由对象
const route = useRoute()

// 计算属性，获取路由名称
const routeName = computed(() => route.meta.title || '')

// 表格数据
const list = ref<User[]>([])

// 加载状态
const listLoading = ref<boolean>(true)

// 分页布局
const layout = ref<string>('total, sizes, prev, pager, next, jumper')

// 总条数
const total = ref<number>(0)

// 显示的列
const checkList = ref<string[]>([])

interface QueryForm {
  page: number
  limit: number
  deptId?: number | string | null
  isExternal?: number // 1:内部人员(红有) 2:外部人员(本系统)
  [key: string]: any
}

// 查询表单
const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
  deptId: null,
})

// 最终显示的列
const finallyColumns = computed(() => tableColumns.value.filter((item: any) => checkList.value.includes(item.label)))

// 查询数据
const queryData = () => {
  queryForm.value.page = 1
  fetchData()
}

const fetchData = async () => {
  listLoading.value = true
  try {
    // 构建查询参数
    const params = { ...queryForm.value }

    // 处理外部部门标识
    params.isExternal = isExternalDepartment.value ? 2 : 1 // 2表示外部人员（本系统），1表示内部人员（红有平台）

    const response = await Public.getDetailApi({
      url: moduleApi,
      params,
    })

    // 处理返回数据
    const data = response.data || response
    if (data && typeof data === 'object' && 'code' in data && data.code === 0 && 'result' in data) {
      const result = data.result as { rows: User[]; count: number }
      list.value = result.rows || []
      total.value = result.count || 0
    } else {
      list.value = []
      total.value = 0
      console.error('获取数据失败:', data && typeof data === 'object' && 'message' in data ? data.message : '未知错误')
    }
  } catch (error) {
    console.error('请求失败:', error)
    list.value = []
    total.value = 0
  } finally {
    listLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

// 当前页改变
const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

// 更新分页信息并重新获取数据
const updatePagination = (params: { page?: number; limit?: number }) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

// 删除行数据
const handleDelete = (id: User) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await Public.delApi({ url: moduleApi, id })
        const data = response.data || response
        if (data && typeof data === 'object' && 'code' in data && data.code === 0) {
          ElMessage.success('删除成功!')
        } else {
          ElMessage.error('删除失败')
        }
        fetchData()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 显示添加表单
const showAddForm = () => {
  form.value = {
    sex: '1',
    platformBelong: isExternalDepartment.value ? '2' : '1', // 根据当前部门类型设置所属平台
    isEnabled: true,
    isManager: false,
  }
  isEditMode.value = false
  showFormDialog.value = true
}

// 处理导入成功
const handleImportSuccess = () => {
  fetchData()
}

// 组件激活时刷新表格布局并获取数据
onActivated(() => {
  fetchData()
})

// 组件挂载前初始化列显示和获取数据
onBeforeMount(() => {
  initializeColumns()
  fetchData()
})

// 初始化列显示
const initializeColumns = () => {
  tableColumns.value.forEach((item: any) => {
    if (!item.noChecked) checkList.value.push(item.label)
  })
}
</script>

<style scoped>
.content-container {
  display: flex;
  gap: 6px;
  height: calc(100vh - 122px);
}

.department-tree {
  width: 300px;
  flex-shrink: 0;
  margin-top: 6px;
}

.user-list {
  flex: 1;
  overflow: hidden;
}

.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}

.header-query {
  display: flex;
  flex-direction: row;
  gap: 12px;
}

.header-query-buttons {
  display: flex;
  gap: 8px;
}
</style>
